﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MarkdownSharp;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;

namespace yasbg
{
    

    class File
    {
        private string head, foot, content, title, date, year, month, day, paragraph, mainBody, filePath;
        private int postsno, counter = 0 ;
        private static int maxpost = 1000;

        public string[] storeTitle = new string[maxpost];
        public string[] storeDate = new string[maxpost];
        public string[] storePost = new string[maxpost];
        public string[] storeLink = new string[maxpost];
        

        //Store IDs
        public int[] storeTitleID = new int[maxpost];
        public int[] storeDateID = new int[maxpost];
        public int[] storePostID = new int[maxpost];
        public int[] storeLinkID = new int[maxpost];
        
        
        public bool ifdebugfile
        {
            get
            {
                return false;
            }
            set
            {
                ifdebugfile = value;
            }
        }
        public File()
        {
            // String assignments for if statements to be true (later on)
            head = "";
            foot = "";
            content = "";
            year = "";
            month = "";
            day = "";
            mainBody = "";
            
        }

        public void UpdateAll()
        {
            WriteMainHtml();
            WriteArchive();

        }

        public void New(string filePath)
        {
            ReadLayout("post");
            
            try
            {
                try
                {
                    TextReader readPostFile = new StreamReader(filePath);
                    title = readPostFile.ReadLine();
                    date = readPostFile.ReadLine();
                    paragraph = readPostFile.ReadToEnd();
                    readPostFile.Close();
                    Markdown HtmlConvert = new Markdown();
                    paragraph = HtmlConvert.Transform(paragraph);
                    mainBody = mainBody + paragraph;
                    Regex DateSplitter = new Regex("/");
                    string[] substringsDate = DateSplitter.Split(date);
                    month = string.Format(substringsDate[0]);
                    day = string.Format(substringsDate[1]);
                    year = string.Format(substringsDate[2]);
                    string newPath = "site/" + year + "/" + month + "/" + day;
                    string newTitle = title + ".html";
                    string htmlFormattedTitle = "<h1>" + title + "</h1>";
                    Directory.CreateDirectory(newPath);
                    filePath = newPath + "/" + newTitle;
                    TextWriter writePostFile = new StreamWriter(filePath);
                    writePostFile.Write(head);
                    writePostFile.Write(htmlFormattedTitle);
                    writePostFile.Write(paragraph);
                    writePostFile.Write(foot);
                    writePostFile.Close();
            
                }
                catch (DirectoryNotFoundException e)
                {
                    Program.errorArg("The file directory was not found. Please check that the posts directory exists.", e.ToString(), ifdebugfile);
 
                }

                
                
            }
            catch (FileNotFoundException e)
            {
                Program.errorArg("The file was not found. Please enter a valid filename.", e.ToString(), ifdebugfile);
               
            }
            
           
        }
        public void ReadLayout(string layoutType)
        {
            string siteLayout = "layout/sitelayout.htm", postLayout = "layout/postlayout.htm", archiveLayout = "layout/archivelayout.htm", wholePostFile, wholeSiteFile, wholeArchiveFile;
            if (layoutType == "site")
            {
                try
                {
                    TextReader layoutSiteReader = new StreamReader(siteLayout);
                    wholeSiteFile = layoutSiteReader.ReadToEnd();
                    layoutSiteReader.Close();
                    Regex splitSite = new Regex("%CONTENT%");
                    string[] subStringSite = splitSite.Split(wholeSiteFile);
                    head = string.Format(subStringSite[0]);
                    content = string.Format(subStringSite[1]);
                    foot = string.Format(subStringSite[2]);
                    try
                    {
                        postsno = int.Parse(content);
                    }
                    catch (FormatException e)
                    {
                        Program.errorArg("There is no number found for the number of posts in the sitelayout.htm. Please give a number and try again.", e.ToString(), ifdebugfile);

                    }


                }
                catch (FileNotFoundException e)
                {
                    Program.errorArg("The file was not found. Please enter a valid filename.", e.ToString(), ifdebugfile);
                }
            }
            else if (layoutType == "post")
            {
                try
                {
                    TextReader layoutPostReader = new StreamReader(postLayout);
                    wholePostFile = layoutPostReader.ReadToEnd();
                    layoutPostReader.Close();
                    Regex splitPost = new Regex("%CONTENT%");
                    string[] subStringPost = splitPost.Split(wholePostFile);
                    head = string.Format(subStringPost[0]);
                    content = string.Format(subStringPost[1]);
                    foot = string.Format(subStringPost[2]);

                }
                catch (FileNotFoundException e)
                {
                    Program.errorArg("The file was not found. Please enter a valid filename.", e.ToString(), ifdebugfile);
                }
            }
            else if (layoutType == "archive")
            {
                try
                {
                    TextReader layoutArchiveReader = new StreamReader(archiveLayout);
                    wholeArchiveFile = layoutArchiveReader.ReadToEnd();
                    layoutArchiveReader.Close();
                    Regex splitArchive = new Regex("%CONTENT%");
                    string[] subStringSite = splitArchive.Split(wholeArchiveFile);
                    head = string.Format(subStringSite[0]);
                    content = string.Format(subStringSite[1]);
                    foot = string.Format(subStringSite[2]);
                    


                }
                catch (FileNotFoundException e)
                {
                    Program.errorArg("The file was not found. Please enter a valid filename.", e.ToString(), ifdebugfile);
                }
            }

        }
        public void AddData()
        {

            try
            {
                string[] filePaths = Directory.GetFiles(@"posts/");
                foreach (string filepath in filePaths)
                {

                    New(filepath);
                    try
                    {

                        if (int.Parse(year) < 99)
                        {
                            filePath = "site/" + year + "/" + month + "/" + day + "/" + title + ".html";
                            int noofdays = (int.Parse(year) * 365) + (int.Parse(month) * 31) + int.Parse(day);
                            storeTitleID.SetValue(noofdays, counter);
                            storeDateID.SetValue(noofdays, counter);
                            storePostID.SetValue(noofdays, counter);
                            storeLinkID.SetValue(noofdays, counter);
                            storeTitle.SetValue(title, counter);
                            storeDate.SetValue(date, counter);
                            storePost.SetValue(paragraph, counter);
                            storeLink.SetValue(filePath, counter);
                            counter++;
                            
                        }
                        else
                            throw new System.ArgumentException("Year of file in wrong syntax", "wrongYearSyntax");
                    }
                    catch (System.ArgumentException e)
                    {
                        Program.errorArg("The year of the date of the file " + filepath + " is not in a correct format (MM/DD/YY). Please check and try again.", e.ToString(), ifdebugfile);
                    }


                }
                
            }
            catch (DirectoryNotFoundException e)
            {
                Program.errorArg("The file directory was not found. Please check that the posts directory exists.", e.ToString(), ifdebugfile);

            }
        }
        public void SortArrays()
        {
            
            Array.Sort(storeTitleID, storeTitle);
            Array.Sort(storeDateID, storeDate);
            Array.Sort(storePostID, storePost);
            Array.Sort(storeLinkID, storeLink);
            
            

        }
        public void WriteMainHtml()
        {
            AddData(); //Add stuff and convert to arrays
            SortArrays();
            ReadLayout("site");
            TextWriter writeMain = new StreamWriter("index.html");
            writeMain.Write(head);
            if (counter - postsno < 0) // we do not want negative posts and empty ones
            {
                postsno = postsno + (counter - postsno);
                for(int arCount = maxpost - 1; arCount > (maxpost - 1 - postsno); arCount--) 
                {
                    
                    try
                    {
                        string LinkandTitle = "<a href=\"" + storeLink[arCount].ToString() + "\">" + "<h2>" + storeTitle[arCount].ToString() + "</h2>" + "</a>";
                        writeMain.Write(LinkandTitle);
                        writeMain.Write(storePost[arCount].ToString());
                    }
                    catch (NullReferenceException e)
                    {
                        Program.errorArg("Whoops! Something really weird happened. Report the stuff underneath to the developer.", e.ToString(), true);
                    }

                    
                }
            }
            else
            {
                for (int arCount = 999; arCount > (999 - postsno); arCount--)
                {
                    
                    try
                    {
                        string LinkandTitle = "<a href=\"" + storeLink[arCount].ToString() + "\">" + "<h2>" + storeTitle[arCount].ToString() + "</h2>" + "</a>";
                        writeMain.Write(LinkandTitle);
                        writeMain.Write(storePost[arCount].ToString());
                    }
                    catch (NullReferenceException e)
                    {
                        Program.errorArg("Whoops! Something really weird happened. Report the stuff underneath to the developer.", e.ToString(), true);
                    }


                }
            }
            writeMain.Write(foot);
            writeMain.Close();

            
        }
        public void WriteArchive()
        {
            //Assumes that WriteHtmlMain() has been executed before
            ReadLayout("archive");
            TextWriter writeArchive = new StreamWriter("archive.html");
            writeArchive.Write(head);
            string[] filePaths = Directory.GetFiles(@"posts/");
            
            if (counter > 0) // More than one post
            {
                for (int arLength = maxpost - 1; arLength > maxpost - 1 - filePaths.Length; arLength--)
                {
                    string LinkandTitle = "<a href=\"" + storeLink[arLength].ToString() + "\">" + "<h2>" + storeTitle[arLength].ToString() + "</h2>" + "</a>";

                    writeArchive.Write(LinkandTitle);


                }
            }
            else
            {
                string LinkandTitle = "<a href=\"" + storeLink[maxpost - 1].ToString() + "\">" + "<h2>" + storeTitle[maxpost - 1].ToString() + "</h2>" + "</a>";
                
                writeArchive.Write(LinkandTitle);
            }
            writeArchive.Write(foot);
            writeArchive.Close();
        }
        
        
           
        
    }
}
